import string

def readfile(path):
    f=open(path,'r')
    lines=f.readlines()
    f.close()
    dictx={}
    for line in lines:
        line =line.strip()
        #print(line)
        if '=' in line:
            ss = line.split('=')
            dictx[ss[0]]=ss[1]
    return dictx
        
def report_dict(title, dictx, report):
    print(title)
    print('--------------')    
    keys = list(dictx.keys())
    keys.sort()
    for key in keys:
        print('%s=%s' % (key, dictx[key]))
        report.append('%s=%s' % (key, dictx[key]))

def save_report(fn, report):
    f=open(fn, 'w')
    f.write('\n'.join(report))
    f.write('\n')
    f.close()
    
def main(path1, path2):
    path1_report=[]
    path2_report=[]
    
    dict2 =readfile(path2)
    dict1 = readfile(path1)
    key2s=list(dict2.keys())
    key2s.sort()
    
    target1 = dict1.get('CONFIG_IDF_TARGET','---')
    target2 = dict2.get('CONFIG_IDF_TARGET','---')
    
    print('path1:%s' % path1)
    print('target1:%s' % target1)
    print('path2:%s' % path2)
    print('target2:%s' % target2)
    print()
    print('Differences: path1 ~ path2')
    print('--------------------------')
    for key in key2s:
        if key in dict1:
            if dict1[key] != dict2[key]:
                print('%s :%s ~ %s' % (key, dict1[key], dict2[key]))
                path1_report.append('%s=%s' % (key, dict1[key]))
                path2_report.append('%s=%s' % (key, dict2[key]))
            del dict1[key]
            del dict2[key]
            
    if len(dict1)>0:
        report_dict('\nIn path1 only:', dict1, path1_report)

    if len(dict2)>0:
        report_dict('\nIn path2 only:', dict2, path2_report)        

    save_report('path1.report', path1_report)
    save_report('path2.report', path2_report)
        
                

def print_usage():
    help="""Usage:
python sdkconfig_diff.py <sdkconfig1> <sdkconfig2>
    - compare <sdkconfig1> with <sdkconfig2> files and print the differences
    
python sdkconfig_diff.py <sdkconfig2>
    - compare local "sdkconfig" with <sdkconfig2> files and print the differences

    
    """
    print(help)
    
if __name__=='__main__':
    import sys
    argv = sys.argv
    if len(argv)>=3:
        path1 = argv[1]
        path2 = argv[2]
    elif len(argv)==2:
        path1 = 'sdkconfig'
        path2 = argv[1]
    else:
        print_usage()
        sys.exit(1)

    main(path1, path2)


